package com.ykefu.assign.netty.http;

import com.ykefu.assign.netty.AssignSessionStore;
import com.ykefu.assign.netty.ChannelRelationStore;
import com.ykefu.assign.netty.ChannelStore;
import com.ykefu.assign.netty.ClientSessionStore;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.Collection;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;

/**
 * @author likai
 * @date 2020/4/8 14:32
 * @email likai@7moor..com
 * @desc websocket 服务配置，后期封装
 */
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServerHandler.class);


    private static final String WEBSOCKET_PATH = "/websocket";

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpRequest) {
            //转http处理
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            //转socket 处理
            WebSocketFrameHandler.handleWebSocketFrame(ctx, (WebSocketFrame) msg, handshaker);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // Handle a bad request.
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST,
                    ctx.alloc().buffer(0)));
            return;
        }
        // Allow only GET methods.
        if (!GET.equals(req.method())) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN,
                    ctx.alloc().buffer(0)));
            return;
        }
        // Send the demo page and favicon.ico
        if ("/".equals(req.uri())) {
            ByteBuf content = WebSocketServerIPageHelper.getContent(getWebSocketLocation(req));
            FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), OK, content);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
            HttpUtil.setContentLength(res, content.readableBytes());
            String s = content.toString(Charset.forName("utf-8"));
            sendHttpResponse(ctx, req, res);
            return;
        }
        if ("/favicon.ico".equals(req.uri())) {
            FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), NOT_FOUND,
                    ctx.alloc().buffer(0));
            sendHttpResponse(ctx, req, res);
            return;
        }

        // Handshake
        String webSocketUri = getWebSocketLocation(req);
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                webSocketUri, null, true, 5 * 1024 * 1024);
        handshaker = wsFactory.newHandshaker(req);
        String uri = req.uri();
        LOGGER.info("请求路径：{},socket路径：{}", uri, webSocketUri);
        //拦截请求标识。
        LOGGER.info("请求唯一标识：{}", ctx.channel().id().asLongText());
        String substring = uri.substring(17);
        ChannelStore.store(substring,ctx.channel());
//        if (new Integer(substring) > 10000) {
//            ClientSessionStore.store(ctx.channel().id().asLongText(), ctx.channel());
//            //如果是客户，则自动分配，并且发送消息
//            if (AssignSessionStore.size() > 0) {
//                String one = AssignSessionStore.getOne();
//                LOGGER.info("分配的坐席链接：{}", one);
//                ChannelRelationStore.store(ctx.channel().id().asLongText(), one);
//            }
//        } else {
//            AssignSessionStore.store(ctx.channel().id().asLongText(), ctx.channel());
//        }
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }


    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // Generate an error page if response getStatus code is not OK (200).
        HttpResponseStatus responseStatus = res.status();
        if (responseStatus.code() != 200) {
            ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }
        // Send the response and close the connection if necessary.
        boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
        HttpUtil.setKeepAlive(res, keepAlive);
        ChannelFuture future = ctx.write(res); // Flushed in channelReadComplete()
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    private static String getWebSocketLocation(FullHttpRequest req) {
        String location = req.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
        if (WebSocketServer.SSL) {
            return "wss://" + location;
        } else {
            return "ws://" + location;
        }
    }
}
